# -*- coding: utf-8 -*-

from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
from odoo.exceptions import UserError


class MrpProductProduce(models.TransientModel):
    _inherit = ['mrp.product.produce']

    lot_uom = fields.Many2one('product.uom', u'辅助单位')
    lot_uom_ratio = fields.Float(u'换算率', digits=(16, 4))
    lot_lenth = fields.Char(u'全长')

    code = fields.Char(u"代码", size=10)
    description = fields.Char(u"说明", size=20)
    board_number = fields.Char(u"内部参考", size=20)
    ref = fields.Char(u"追踪号")

    idle = fields.Boolean(u'呆滞', default=False)
    sale_type = fields.Selection([('0', u'内销'), ('1', u'外销')], u'销售类型')

    lot_uom_qty = fields.Float(u'辅助单位数量', compute='_compute_lot_uom_qty')
    lot_for_copy = fields.Many2one('stock.production.lot', u'信息复制')

    @api.model
    def default_get(self, fields):
        res = super(MrpProductProduce, self).default_get(fields)
        if self._context and self._context.get('active_id'):
            production = self.env['mrp.production'].browse(self._context['active_id'])
            res['ref'] = production.track_number
        return res


    @api.onchange('lot_uom')
    def onchange_lot_uom(self):
        if self.lot_uom:
            if self.lot_uom.uom_type=='bigger':
                self.lot_uom_ratio = self.lot_uom.factor
            elif self.lot_uom.uom_type=='smaller':
                self.lot_uom_ratio = 1/self.lot_uom.factor
            else:
                self.lot_uom_ratio = 1

    @api.onchange('lot_for_copy')
    def onchange_lot_for_copy(self):
        if self.lot_for_copy:
            self.lot_uom = self.lot_for_copy.lot_uom.id
            self.lot_uom_ratio = self.lot_for_copy.lot_uom_ratio and self.lot_for_copy.lot_uom_ratio or 1
            self.ref = self.lot_for_copy.ref
            self.lot_uom_qty = self.product_qty / self.lot_uom_ratio

    @api.depends('lot_uom_ratio')
    def _compute_lot_uom_qty(self):
        for produce in self:
            if produce.lot_uom_ratio > 0:
                produce.lot_uom_qty = produce.product_qty / produce.lot_uom_ratio

    @api.multi
    def do_produce(self):
        if self.product_tracking and not self.lot_id:
            lot_id = self.env['stock.production.lot'].create({
                'product_id': self.product_id.id,
                'lot_uom': self.lot_uom.id,
                'lot_uom_ratio': self.lot_uom_ratio,
                'lot_lenth': self.lot_lenth,
                'code': self.code,
                'description': self.description,
                'board_number': self.board_number,
                'ref': self.ref,
                'sale_type': self.sale_type,
            })
            self.lot_id = lot_id.id
            # raise UserError(u'对不起，该产品必须有批次号。')
        return super(MrpProductProduce, self).do_produce()

    @api.multi
    def check_finished_move_lots(self):
        super(MrpProductProduce, self).check_finished_move_lots()
        lots = self.env['stock.move.lots']
        produce_move = self.production_id.move_finished_ids.filtered(
            lambda x: x.product_id == self.product_id and x.state not in ('done', 'cancel'))
        if produce_move.product_id.tracking != 'none':
            for move_lot in produce_move.active_move_lot_ids:
                move_lot.write({
                    'lot_uom': self.lot_uom.id,
                    'lot_uom_ratio': self.lot_uom_ratio,
                    'lot_lenth': self.lot_lenth,
                    'code': self.code,
                    'description': self.description,
                    'board_number': self.board_number,
                    'ref': self.ref,
                    'sale_type': self.sale_type,
                })
        return True


class stock_move(models.Model):
    _inherit = 'stock.move'
    ref = fields.Char(u'追踪号',related='production_id.track_number')

class stock_move_lots(models.Model):
    _inherit = 'stock.move.lots'

    picking_type = fields.Many2one('stock.picking.type', u'调拨类型')
    product_id = fields.Many2one('product.product', u'产品')
    production_id = fields.Many2one('mrp.production', u'成品的生产单')
    raw_material_production_id = fields.Many2one('mrp.production', u'材料的生产单')
    related_lot_id = fields.Many2one('stock.production.lot', u'完工/批次',related='lot_id',readonly=True)
    lot_for_copy = fields.Many2one('stock.production.lot', u'信息复制')
    lot_uom = fields.Many2one('product.uom', u'辅助单位')
    lot_uom_qty = fields.Float(u'辅助单位数量')
    lot_uom_ratio = fields.Float(u'换算率', digits=(16, 4))
    lot_lenth = fields.Char(u'全长')
    ref = fields.Char(u'追踪号')

    code = fields.Char(u"代码", size=10)
    description = fields.Char(u"说明", size=20)
    board_number = fields.Char(u"内部参考", size=20)

    # create_lot = fields.Boolean(u'创建批次',default=False)

    # @api.model
    # def default_get(self, fields):
    #     res = super(stock_move_lots, self).default_get(fields)
    #     if 'move_id' in fields and not res.get('move_id') and self._context.get('active_model') == 'stock.move' and self._context.get('active_id'):
    #         res['move_id'] = self._context['active_id']
    #     # if 'product_qty' in fields and not res.get('product_qty') and res.get('move_id'):
    #         res['quantity'] = self.env['stock.move'].browse(res.get['move_id']).product_uom_qty
    #     return res

    # @api.onchange('lot_uom')
    # def onchange_lot_uom(self):
    #     if self.lot_uom:
    #         self.lot_uom_ratio = self.lot_uom.factor_inv
            # if self.lot_uom.uom_type=='bigger':
            #     self.lot_uom_ratio = self.lot_uom.factor
            # elif self.lot_uom.uom_type=='smaller':
            #     self.lot_uom_ratio = 1/self.lot_uom.factor
            # else:
            #     self.lot_uom_ratio = 1

    @api.onchange('lot_name')
    def onchange_lot_name(self):
        if self.lot_name and not self.lot_id:
            self.lot_name = None
        if self.lot_name and self.lot_id:
            self.lot_name = self.lot_id.display_name

    @api.onchange('lot_for_copy')
    def onchange_lot_for_copy(self):
        if self.lot_for_copy:
            self.lot_lenth = self.lot_for_copy.lot_lenth
            self.code = self.lot_for_copy.code
            self.description = self.lot_for_copy.description
            self.board_number = self.lot_for_copy.board_number
            self.lot_uom = self.lot_for_copy.lot_uom.id
            self.lot_uom_ratio = self.lot_for_copy.lot_uom_ratio
            self.ref = self.lot_for_copy.ref
            self.quantity_done = self.lot_uom_qty * self.lot_uom_ratio
            self.mrp_platform = self.lot_for_copy.mrp_platform
            self.mrp_shift = self.lot_for_copy.mrp_shift
            self.remark_one = self.lot_for_copy.remark_one
            self.remark_two = self.lot_for_copy.remark_two

    @api.onchange('lot_id')
    def onchange_lot_id(self):
        if self.lot_id:
            self.lot_lenth = self.lot_id.lot_lenth
            self.code = self.lot_id.code
            self.description = self.lot_id.description
            self.board_number = self.lot_id.board_number
            self.lot_uom_ratio = self.lot_id.lot_uom_ratio
            self.lot_uom = self.lot_id.lot_uom.id

    @api.onchange('lot_uom_qty', 'lot_uom_ratio')
    def onchange_lot_uom_ratio(self):
        self.quantity_done = self.lot_uom_qty * self.lot_uom_ratio

    @api.onchange('lot_lenth', 'code', 'description', 'board_number')
    def onchange_something(self):
        if self.lot_id:
            self.lot_id.lot_lenth = self.lot_lenth
            self.lot_id.code = self.code
            self.lot_id.description = self.description
            self.lot_id.board_number = self.board_number

    @api.onchange('quantity_done')
    def onchange_quantity_done(self):
        if not self.lot_id and self.quantity_done> 0 and self.production_id:
            lot_id = self.env['stock.production.lot'].create({
                'product_id': self.move_id.product_id.id,
                # 字段赋值
                'lot_uom': self.lot_uom.id,
                'lot_uom_ratio': self.lot_uom_ratio,
                'lot_lenth': self.lot_lenth,
                'ref': self.ref,
                'code': self.code,
                'description': self.description,
                'board_number': self.board_number,
                'mrp_platform': self.mrp_platform,
                'mrp_shift': self.mrp_shift,
                'remark_one': self.remark_one,
                'remark_two': self.remark_two,
            })
            self.lot_id = lot_id.id
            self.lot_name = lot_id.display_name
